package cn.wei.reallyenjoy.comment.controller;



import cn.wei.reallyenjoy.comment.pojo.vo.CommentVO;
import cn.wei.reallyenjoy.comment.pojo.vo.DiaryCommentVO;
import cn.wei.reallyenjoy.comment.pojo.vo.DiaryCommentsListVO;
import cn.wei.reallyenjoy.comment.service.CommentsService;
import cn.wei.reallyenjoy.common.result.Result;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 评论表 前端控制器
 * </p>
 *
 * @author Wei
 * @since 2021-11-28
 */
@RestController
@Api(tags = "评论接口")
@RequestMapping("/comments")
public class CommentsController {

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private CommentsService commentsService;

    @ApiOperation("根据日记id获取评论列表")
    @GetMapping("/getCommentsByDiaryId/{diaryId}")
    public Result getCommentsByDiaryId(@PathVariable("diaryId") Long diaryId){
        List<DiaryCommentVO> diaryComments = commentsService.getCommentsByDiaryId(diaryId);

        DiaryCommentsListVO diaryCommentsListVO = new DiaryCommentsListVO();
        diaryCommentsListVO.setDiaryCommentList(diaryComments);
        return Result.succ("ok，serverPort："+serverPort,diaryCommentsListVO);
    }

    @ApiOperation("用户评论日记")
    @PostMapping("/userComment")
    public Result userCommentDiary(CommentVO commentVO){
        commentsService.userCommentDiary(commentVO);
        return Result.succ("评论成功",null);
    }

    /**
     * 超时访问，演示降级
     * @param diaryId
     * @return
     */

    @HystrixCommand(fallbackMethod = "getCommentsByDiaryId_TimeOutHandle",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="4000")
    })
    @ApiOperation("演示Hystrix服务降级：根据日记id获取评论列表")
    @GetMapping("/showHystrixByDiaryId/{diaryId}")
    public Result showHystrixByDiaryId(@PathVariable("diaryId") Long diaryId){
//        演示发生异常，服务端进行服务降级
//        int a= 10/0;
        List<DiaryCommentVO> diaryComments = commentsService.getCommentsByDiaryId(diaryId);

        DiaryCommentsListVO diaryCommentsListVO = new DiaryCommentsListVO();
        diaryCommentsListVO.setDiaryCommentList(diaryComments);
//        try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
        return Result.succ("ok，showHystrixByDiaryId："+diaryId+"耗费3秒,"+"serverPort："+serverPort,diaryCommentsListVO);
    }


    public Result getCommentsByDiaryId_TimeOutHandle(Long diaryId)
    {
        return Result.fail("系统繁忙或异常请稍后再尝试：showHystrixByDiaryId:TimeOutError,diaryId:"+diaryId);
    }


}

